﻿
using Newtonsoft.Json;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Models.Common;
using Swashbuckle.AspNetCore.SwaggerGen;
using System.Collections;
using ServiceWeb.DBGateway;
using Models.JsonResultModel;
using NuGet.Versioning;
using SQLitePCL;
using UtilsBase;
using UtilsORM;
using UtilsORM.MySqlData;
using GatewayServer.Common;

namespace GatewayServer.Controllers
{
    public class DeviceLinkageController : BaseMagerController
    {
        EFYihongIotContext ef = new EFYihongIotContext();
        // GET: Mager_Department
        public IActionResult list(IFormCollection FC, HttpReqModel httpRequest, iot_product reqProduct, int PageIndex = 1, int PageSize = 15, string type = "1")
        {
            ViewData["reqProduct"] = reqProduct;
            List<SugarParameter> sugarParameters = new List<SugarParameter>();
            int totalRecord = 0;
            string sqlwhere = " ";


            if (!string.IsNullOrEmpty(reqProduct.p_guid))
            {
                sqlwhere = sqlwhere + "  and l_p_guid = @l_p_guid ";
                sugarParameters.Add(new SugarParameter("l_p_guid", reqProduct.p_guid));

            }
            //else
            //{
            //    sqlwhere = sqlwhere + "   and l_is_template=0 ";
            //}


            if (!string.IsNullOrEmpty(httpRequest.name))
            {
                sqlwhere = sqlwhere + " and l_title like CONCAT('%',@name,'%') ";
                sugarParameters.Add(new SugarParameter("name", httpRequest.name));

            }
            if (!string.IsNullOrEmpty(FC["hid_pageIndex"]))
            {
                PageIndex = int.Parse(FC["hid_pageIndex"].ToString());

            }

            if (!string.IsNullOrEmpty(httpRequest.status))
            {
                //设置状态
                sqlwhere = sqlwhere + " and l_status=@status";
                sugarParameters.Add(new SugarParameter("status", httpRequest.status));
            }


            string sql = "select  * from iot_device_linkage where 1= 1  " + sqlwhere;
            DataTable dt = MySqlYihongIot.getPageDataTable(PageIndex, PageSize, sql, sugarParameters, "l_id desc", ref totalRecord);


            Dictionary<string, DataTable> list1 = new Dictionary<string, DataTable>();
            Dictionary<string, DataTable> list2 = new Dictionary<string, DataTable>();
            foreach (DataRow dr in dt.Rows)
            {
                //                string sqlitem = @"	select distinct d_code,lc_l_guid,d_guid,d_name,lc_operation,lc_key,lc_value,lc_value_rule,lc_status,v_name,dc_name,lc_id   from  iot_device_linkage_condition 
                //	inner join iot_device on d_guid=lc_d_guid 
                //inner join iot_device_model_variable_relation on mv_model_guid=d_model_guid
                //	 left join iot_device_command on dc_model_guid=d_model_guid 	 and lc_operation='follow' and lc_key=dc_key
                //	inner join iot_device_model_variable on  mv_v_guid=v_guid   	and lc_operation='main'and lc_key=v_key
                //		where lc_l_guid='" + dr["l_guid"] + "' order by lc_id asc";
                //                DataTable item = MySqlYihongIot.GetDataTable(sqlitem);


                string mainsql = "select  lc_p_model_no,d_code,lc_l_guid,d_guid,d_name,lc_operation,lc_key,lc_value,lc_value_rule,lc_status,v_name,lc_id,v_guid   " +
                    "from  iot_device_linkage_condition  inner join iot_device on d_guid=lc_d_guid  inner join iot_device_model_variable_relation on" +
                    " mv_model_guid=d_model_guid inner join iot_device_model_variable on  mv_v_guid=v_guid   " +
                    "and lc_operation='main' and lc_key=v_key where lc_l_guid='" + dr["l_guid"] + "' order by lc_id asc";
                DataTable item1 = MySqlYihongIot.GetDataTable(mainsql);
                list1.Add(dr["l_guid"].ToString().ToLower(), item1);

                string followsql = "select  lc_p_model_no,d_code,lc_l_guid,d_guid,d_name,lc_operation,lc_key,lc_value,lc_value_rule,lc_status,dc_name,lc_id   from  iot_device_linkage_condition   " +
                    "  inner join iot_device on d_guid = lc_d_guid     left join iot_device_command on dc_model_guid = d_model_guid   " +
                    "   and lc_operation = 'follow' and lc_key = dc_key where lc_l_guid='" + dr["l_guid"] + "' order by lc_id asc";
                DataTable item2 = MySqlYihongIot.GetDataTable(followsql);
                list2.Add(dr["l_guid"].ToString().ToLower(), item2);
            }

            ViewData["ItemData1"] = list1;
            ViewData["ItemData2"] = list2;
            ViewData["DataList"] = dt;

            ViewBag.PageSize = PageSize;
            ViewBag.RecordCount = totalRecord;//总条数
            ViewBag.PageCount = totalRecord % PageSize == 0 ? totalRecord / PageSize : totalRecord / PageSize + 1;//分的页数
            ViewBag.PageIndex = PageIndex;//当前页码
            return View(httpRequest);
        }
        public IActionResult edit(HttpReqModel httpReqModel, iot_product product)
        {
            ViewBag.l_p_guid = product.p_guid;
            if (httpReqModel.order == "upd")
            {
                ViewBag.l_guid = httpReqModel.guid.ToString();
            }
            else
            {
                ViewBag.l_guid = Guid.NewGuid().ToString();
            }
            ViewBag.order = httpReqModel.order;
            return View();
        }
        public RespResultData getLinkage(HttpReqModel httpReqModel)
        {
            return RespResult.Sucess(new DBIotDeviceLinkage().getLinkage(httpReqModel.guid));
        }
        //public RespResultData getWarn(HttpReqModel httpReqModel)
        //{
        //    return RespResult.Sucess(new DBIotDeviceWarn().getWarn(httpReqModel.guid));
        //}

        public JsonResult savelinkage(IFormCollection FC, HttpReqModel httpRequest, iot_device_linkage linkage)
        {
            new DBIotDeviceLinkage().saveAll(LoginUserInfo, linkage);//, int.Parse(FC["w_status"].ToString())

            return ReturnJsonResult.Sucess();
        }

        public JsonResult saveTemp(IFormCollection FC, HttpReqModel httpRequest, iot_device_linkage linkage)
        {

            new DBIotDeviceLinkage().saveAll(LoginUserInfo, linkage);
            if (httpRequest.type == "main")
            {

                iot_device_linkage_condition iot_Device_Linkage_Condition = new iot_device_linkage_condition();
                iot_Device_Linkage_Condition.lc_guid = Guid.NewGuid().ToString();
                iot_Device_Linkage_Condition.lc_d_guid = FC["seldevice"];
                iot_Device_Linkage_Condition.lc_operation = "main";
                iot_Device_Linkage_Condition.lc_dv_guid = FC["selvar"];
                iot_Device_Linkage_Condition.lc_value = FC["conditionValue"];
                iot_Device_Linkage_Condition.lc_vr_guid = FC["selvarvalue"];
                iot_Device_Linkage_Condition.lc_l_guid = FC["l_guid"];


                new DBIotDeviceLinkageCondition().saveAll(LoginUserInfo, iot_Device_Linkage_Condition);
            }
            else if (httpRequest.type == "follow")
            {
                iot_device_linkage_condition iot_Device_Linkage_Condition = new iot_device_linkage_condition();
                iot_Device_Linkage_Condition.lc_guid = Guid.NewGuid().ToString();
                iot_Device_Linkage_Condition.lc_d_guid = FC["seldevice2"];
                iot_Device_Linkage_Condition.lc_operation = "follow";
                iot_Device_Linkage_Condition.lc_dc_guid = FC["lc_dc_guid"];
                iot_Device_Linkage_Condition.lc_l_guid = FC["l_guid"];
                iot_Device_Linkage_Condition.lc_value = FC["lc_value"];
                iot_Device_Linkage_Condition.lc_repeat_count = int.Parse(FC["lc_repeat_count"].ToString());
                iot_Device_Linkage_Condition.lc_repeat_interval = int.Parse(FC["lc_repeat_interval"].ToString());
                new DBIotDeviceLinkageCondition().saveAll(LoginUserInfo, iot_Device_Linkage_Condition);
            }


            return ReturnJsonResult.Sucess();
        }
        public RespResultData getConditionListTemp(HttpReqModel httpReqModel)
        {

            List<Dictionary<string, string>> list = new DBIotDeviceLinkageCondition().getEditConitionItemList(httpReqModel, httpReqModel.type);
            return RespResult.Sucess(list);


        }

        public RespResultData delTemp(IFormCollection FC, HttpReqModel httpReqModel)
        {
            EFYihongIotContext ef = new EFYihongIotContext();

            iot_device_linkage_condition item = ef.iot_device_linkage_condition.Where(c => c.lc_guid == httpReqModel.guid).FirstOrDefault();
            if (item != null)
            {
                ef.iot_device_linkage_condition.Remove(item);
                ef.SaveChanges();
            }
            //查询是否还有子项，没有的话，删除主记录
            iot_device_linkage_condition condition = ef.iot_device_linkage_condition.Where(c => c.lc_l_guid == item.lc_l_guid).FirstOrDefault();
            if (condition == null)
            {
                iot_device_linkage linkage = ef.iot_device_linkage.Where(c => c.l_guid == item.lc_l_guid).FirstOrDefault();
                if (linkage != null)
                {
                    ef.iot_device_linkage.Remove(linkage);
                    ef.SaveChanges();
                }
            }
            return RespResult.Sucess();
        }
        public JsonResult delLinkage(IFormCollection FC)
        {
            iot_device_linkage getModel;
            List<iot_device_linkage> List = new List<iot_device_linkage>();

            List<string> str_param = Request.Form.Keys.ToList();
            for (int i = 0; i < str_param.Count; i++)
            {
                if (str_param[i].ToLower().Contains("checkbox") && !string.IsNullOrEmpty(Request.Form[str_param[i]]))
                {
                    string[] cbparam = Request.Form[str_param[i].ToString()].ToString().Split(',');
                    foreach (string pnum in cbparam)
                    {
                        getModel = new iot_device_linkage();
                        getModel.l_guid = pnum;
                        List.Add(getModel);
                    }
                }
            }
            if (List.Count > 0)
            {
                if (new DBIotDeviceLinkageCondition().del(List))
                {
                    return ReturnJsonResult.Sucess();
                }
            }

            return ReturnJsonResult.Faild();
        }


        public JsonResult getHasVariableDevice(HttpReqModel httpReqModel, iot_product product)
        {
            List<iot_device> devices = new DBIotDeviceVariable().getHasVariableDevice();
            if (!string.IsNullOrEmpty(product.p_guid))
            {
                devices = devices.Where(c => c.d_p_guid == product.p_guid).ToList();
            }
            else
            {
                devices = devices.ToList();
            }
            return ReturnJsonResult.Sucess(devices);
        }
        public JsonResult getVariableByDevice(HttpReqModel httpReqModel)
        {
            return ReturnJsonResult.Sucess(new DBIotDeviceVariable().getVariableByDevice(LoginUserInfo.userCompanyGuid, httpReqModel.guid, httpReqModel.export));
        }
        public JsonResult getDeviceModel(HttpReqModel httpReqModel)
        {
            iot_device device = new DBIotDevice().getDevice(httpReqModel.guid);
            return ReturnJsonResult.Sucess(new DBIotDeviceModel().getModel(device.d_model_guid));
        }
        public JsonResult getVariable(HttpReqModel httpReqModel)
        {

            return ReturnJsonResult.Sucess(new DBIotDeviceVariable().getVariable(httpReqModel.guid));
        }
        public JsonResult getVariableValueRlue(HttpReqModel httpReqModel)
        {
            List<iot_device_model_variable> iot_Device_Variables = new DBIotDeviceVariable().getVariableByGuid(LoginUserInfo.userCompanyGuid, httpReqModel.guid, httpReqModel.export);
            if (iot_Device_Variables.Count > 0)
            {
                return ReturnJsonResult.Sucess(new DBIotDeviceVariableValueRlue().getVariableValueRlueList(iot_Device_Variables[0].v_value_type));
            }
            return ReturnJsonResult.Faild();
        }

        public RespResultData getCommandList(HttpReqModel httpReqModel)
        {
            iot_device device = new DBIotDevice().getDevice(httpReqModel.guid);

            return RespResult.Sucess(new DBIotDeviceCommand().getCommandList(device.d_model_guid));
        }

        public RespResultData changeStatus(HttpReqModel httpReqModel)
        {
            new DBIotDeviceLinkage().changeStatus(httpReqModel.guid);
            return RespResult.Sucess();
        }
    }
}